package com.example.kotlin.proxy

import com.example.kotlin.extension.*
import com.example.kotlin.model.*
import org.springframework.stereotype.*
import xyz.erupt.annotation.`fun`.*
import xyz.erupt.jpa.dao.*
import javax.annotation.*

@Component
class BookDataProxy : DataProxy<Book> {

    @Resource
    private lateinit var eruptDao: EruptDao

    // 数据库查询的book对象不包含临时字段categoryId,在传给前端之前要先填充这个字段
    override fun editBehavior(book: Book?) {
        val category = book?.category
        checkNotNull(category) { return }
        book.categoryId = category.id
    }

    // 前端传递过来的book对象不包含category字段,因此在写入数据库之前要先将category查出来
    override fun beforeAdd(book: Book?) {
        val id = book?.categoryId
        checkNotNull(id) { return }
        val category = eruptDao.queryEntityById<Category>(id)
        checkNotNull(category) { return }
        book.category = category
    }

    // 前端传递过来的book对象不包含category字段,因此在写入数据库之前要先将category查出来
    override fun beforeUpdate(book: Book?) {
        val id = book?.categoryId
        checkNotNull(id) { return }
        val category = eruptDao.queryEntityById<Category>(id)
        checkNotNull(category) { return }
        book.category = category
    }
}
